﻿Imports System
Imports System.Data
Imports System.Data.SqlClient


Public Class Frm_INTPost


    Implements IDServer.IDServer.IDServer


    Dim strsql As String
    Dim strsqlevent As String
    Dim ds As New DataSet
    Dim rstmain As New DataSet
    Dim rst As New DataSet

    Private WithEvents MainForm As Frm_MainForm


    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property





    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd

    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    End Sub

    '' 判斷但錢倉庫是否已經關帳
    Public Function IscopiedFvalue(ByVal stor As String) As Boolean
        If isexistedstorehouse(stor) = True Then
            Dim strfvalue As String = ""
            Dim returnfvalue As String
            strfvalue = "select fvalue  from BSC_SystemProfile where Fcategory='store' and Fkey='period_'+'" & PubCompanyCode & "'+'_status'"

            Dim Dt As DataTable
            Dt = Exec(strfvalue, E_ExecType.DataTable)
            If Dt.Rows.Count <= 0 Then
                MessageBox.Show("請設置當前倉庫的期別", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Return False
                Exit Function
            End If
            returnfvalue = GetValue(strfvalue)
            If Val(returnfvalue) = 1 Then
                Return False
            Else
                Return True
            End If
        Else
            Return False
        End If
    End Function

    ''  判斷當前用戶所在部門有沒有對應的倉庫

    Public Function isexistedstorehouse(ByVal stor As String) As Boolean
        Try
            Dim strsqlstorehouse As String
            Dim rststorehouse As New DataSet
            strsqlstorehouse = "select * from BSC_storehouse a, Bsc_dept b  where  a.fcode=b.fcode  and  b.fcode='" & stor & "'"
            rststorehouse = ReturnDataset(strsqlstorehouse)
            If rststorehouse.Tables(0).Rows.Count > 0 Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString + Err.Description, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Function

    '' 讀當前倉庫期別
    Public Function readcurrentperiod(ByVal stor As String)

        Try
            If isexistedstorehouse(stor) = True Then
                Dim strsql As String
                Dim rstcheckbill As New DataSet
                strsql = "select * from  BSC_SystemProfile where Fcategory='store' and fkey='period_'+'" & stor & "' "
                rstcheckbill = ReturnDataset(strsql)
                For Each period As DataRow In rstcheckbill.Tables(0).Rows
                    Return period("fvalue")
                Next
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString + Err.Description, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Function

    Public Function Bindhash(ByVal index As Integer) As Hashtable
        Try
            Dim Mhash As New Hashtable
            With Mhash
                Select Case index
                    Case 0
                        .Add("checknum", "盤點單號")
                        .Add("period", "當前期別")
                        .Add("storehouse", "倉庫")
                        .Add("checkman", "盤點員")
                        .Add("checkdate", "盤點日期")
                        .Add("checkcomputername", "電腦編號")
                        .Add("confirmman", "盤點確認")
                        .Add("confirmdate", "確認日期")
                        .Add("confirmcomputername", "確認電腦名")
                        .Add("billstatus", "單狀態")
                    Case 1
                        .Add("checknum", "盤點單號")
                        .Add("barcode", "條碼")
                        .Add("batch", "批次")
                        .Add("status", "狀態")
                        .Add("place", "庫位")
                        .Add("qty", "數量")
                        .Add("unit", "單位")
                    Case 2
                        .Add("period", "期別")
                        .Add("storehouse", "倉庫")
                        .Add("management", "事件記載")
                        .Add("operator", "操作人")
                        .Add("operatetime", "操作日期")
                        .Add("computername", "操作電腦")
                    Case 3
                        .Add("period", "期別")
                        .Add("storehouse", "倉庫")
                        .Add("barcode", "條碼")
                        .Add("batch", "批次")
                        .Add("status", "狀態")
                        .Add("beginqty", "期初庫存")
                        .Add("inqty", "本月入庫")
                        .Add("outqty", "本月出庫")
                        .Add("endqty", "實際庫存")
                        .Add("place", "庫位")
                End Select
                Return Mhash
            End With
        Catch ex As Exception
            MessageBox.Show(ex.ToString + Err.Description, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function
    Private Sub BindDGVOperationevents()
        Try
            Dim Mtable As New DataTable
            With Mtable
                .Columns.Add("period")
                .Columns.Add("storehouse")
                .Columns.Add("management")
                .Columns.Add("operator")
                .Columns.Add("operatetime")
                .Columns.Add("computername")
            End With
            Dim rst As New DataSet
            rst = New DataSet
            rst.Tables.Add(Mtable)
            Me.DGVevent.DataSource = rst.Tables(0)

            With DGVevent
                For i As Integer = 0 To .Columns.Count - 1
                    Dim Mkey As String = .Columns(i).Name
                    Dim Captionstr As String = Bindhash(2).Item(Mkey)
                    .Columns(i).HeaderText = Captionstr
                Next

                .AllowUserToResizeColumns = True
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader

                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .ReadOnly = True
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter


            End With
        Catch ex As Exception

        End Try
    End Sub

    Private Sub bindDataGridViewstoragedetail()
        Dim Mtable As New DataTable
        Try
            With Mtable
                .Columns.Add("period")
                .Columns.Add("storehouse")
                .Columns.Add("barcode")
                '.Columns.Add("replace(barcode,'*','')")
                .Columns.Add("batch")
                .Columns.Add("status")
                .Columns.Add("beginqty")
                .Columns.Add("inqty")
                .Columns.Add("outqty")
                .Columns.Add("endqty")
                .Columns.Add("place")
            End With
            Dim dsstorage As New DataSet
            dsstorage = New DataSet
            dsstorage.Tables.Add(Mtable)
            DataGridViewstoragedetail.DataSource = dsstorage.Tables(0)

            With DataGridViewstoragedetail
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mkey As String = .Columns(i).Name
                    Dim captionstr As String = Bindhash(3).Item(mkey)
                    .Columns(i).HeaderText = captionstr
                Next

                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader

                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .ReadOnly = True
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With
        Catch ex As Exception
            MessageBox.Show(ex.ToString + Err.Description, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

    Private Sub btnaddnew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnaddnew.Click
        Try
            Me.Cursor = Cursors.WaitCursor

            If Me.Chk1.Checked = False Then
                MessageBox.Show("必須統計ＰＯＳ出庫", Msg.CompanyName, MessageBoxButtons.OK)
                Exit Sub
            End If
            If Me.Chk2.Checked = False Then
                MessageBox.Show("必須統計庫存管理出入庫", Msg.CompanyName, MessageBoxButtons.OK)
                Exit Sub
            End If
            If Me.Chk3.Checked = False Then
                MessageBox.Show("必須統計當前庫存", Msg.CompanyName, MessageBoxButtons.OK)
                Exit Sub
            End If
            If Me.Chk4.Checked = False Then
                MessageBox.Show("必須計算單價金額", Msg.CompanyName, MessageBoxButtons.OK)
                Exit Sub
            End If
            If Me.Chk5.Checked = False Then
                MessageBox.Show("必須更新當前期別狀態", Msg.CompanyName, MessageBoxButtons.OK)
                Exit Sub
            End If
            If Me.Chk6.Checked = False Then
                MessageBox.Show("必須更新當前庫存狀態", Msg.CompanyName, MessageBoxButtons.OK)
                Exit Sub
            End If
            If isexistedstorehouse(PubCompanyCode) = False Then
                MessageBox.Show("當前用戶所在部門，沒有對應的倉庫", Msg.CompanyName, MessageBoxButtons.OK)
                Exit Sub
            End If
            If Me.Txtcurrentperiod.Text.Length = 0 Then
                MessageBox.Show("請求確認當前倉庫的當前其別", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

            Dim Chkbill As String = ""
            Dim Recordcount As String = ""
            Dim Chkdst As New DataSet
            Dim firstdate As String = currentperiodfirstday(PubCompanyCode) + "-01"
            Dim lastdate As String = currentperiodlastday(PubCompanyCode)

            Chkbill = "select * from (select *, storehouse=(case tradetype when '+' then Tostore  else  fromstore end)  from  stor_trademaster) a where storehouse ='" & PubCompanyCode & "' and Isnull(BoStatus,'') In ('A','C')  and deliverdate>='" & firstdate & "' and deliverdate<='" & lastdate & "'"

            Chkdst = ReturnDataset(Chkbill)
            Recordcount = Chkdst.Tables(0).Rows.Count

            If Recordcount > 0 Then
                MessageBox.Show("関賬前請確認所有單據都已經審核！共有" + Recordcount + "單沒有審核", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If


            If IscopiedFvalue(PubCompanyCode) = False Then
                Try
                    Dim strsql As String = ""
                    Dim Ischangeperiodstatus As Int32 = IIf(Me.Chk5.Checked = True, 1, 0)
                    Dim Ischangestorsatus As Int32 = IIf(Me.Chk5.Checked = True, 1, 0)
                    Dim storagehistorycnn As New SqlClient.SqlConnection
                    Dim ds As New SqlClient.SqlCommand

                    storagehistorycnn = GetConn()
                    If storagehistorycnn.State = ConnectionState.Closed Then
                        storagehistorycnn.Open()
                    End If
                    strsql = "exec Accountclose '" & PubCompanyCode & "','" & Ischangeperiodstatus & "','" & Ischangestorsatus & "'"
                    ds.CommandText = strsql
                    ds.Connection = storagehistorycnn
                    ds.ExecuteNonQuery()
                    MessageBox.Show("関賬成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Me.btnaddnew.Enabled = False
                    Me.Btnunaddnew.Enabled = True
                    Me.Btnpass.Enabled = True
                Catch ex As Exception
                    MessageBox.Show(ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            Else
                MessageBox.Show("已經関賬，若要重復建賬，請先反関賬", Msg.CompanyName, MessageBoxButtons.OK)
                Me.btnaddnew.Enabled = False
                Me.Btnunaddnew.Enabled = True
                Me.Btnpass.Enabled = True
            End If
        Catch ex As Exception
            MessageBox.Show("btnaddnew_Click:" + ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    'Selected the CheckItems 

    'Public Sub Selectedcheck()
    'End Sub
    Public Sub Enablecontrol(ByVal B As Boolean)


        Try
            Me.Chk1.Checked = B
            Me.Chk2.Checked = B
            Me.Chk3.Checked = B
            Me.Chk4.Checked = B
            Me.Chk5.Checked = B
            Me.Chk6.Checked = B

            Me.Chk1.Enabled = False
            Me.Chk2.Enabled = False
            Me.Chk3.Enabled = False
        Catch ex As Exception

        End Try

    End Sub


    Private Sub Frm_INTPost_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try
            Dim B As Boolean = True
            Enablecontrol(B)
            BindDGVOperationevents()
            bindDataGridViewstoragedetail()
            Me.Txtcurrentperiod.Text = readcurrentperiod(PubCompanyCode)

            If IscopiedFvalue(PubCompanyCode) = True Then
                Me.btnaddnew.Enabled = False
                Me.Btnunaddnew.Enabled = True
                Me.Btnpass.Enabled = True
            Else
                Me.btnaddnew.Enabled = True
                Me.Btnunaddnew.Enabled = False
                Me.Btnpass.Enabled = False
            End If
        Catch ex As Exception
            MessageBox.Show(Err.Description + ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub SplitContainer2_Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles SplitContainer2.Panel1.Paint

    End Sub

    Private Sub Btnfind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnfind.Click
        Dim Frm As New Frm_Wating
        Try

            Frm.Show()
            Dim stragesql As String = ""
            Dim eventssql As String = ""
            Dim dststorage As New DataSet
            'Dim dstevents As New DataSet

            stragesql = "select period,storehouse,barcode,batch,status,beginqty,inqty,outqty,endqty from stor_storagehistory where 1=1 " & vbCrLf
            eventssql = "select * from dbo.Stor_StorageOperationevents where 1=1 " & vbCrLf

            If Me.Txtstor.Text.Length > 0 Then
                stragesql += "and storehouse='" & Trim(Txtstor.Text) & "'" & vbCrLf
                eventssql += "and storehouse='" & Trim(Txtstor.Text) & "'" & vbCrLf
            End If
            If Me.Txtperiod.Text.Length > 0 Then
                stragesql += "and period='" & Trim(Txtperiod.Text) & "'" & vbCrLf
                eventssql += "and period='" & Trim(Txtperiod.Text) & "'" & vbCrLf
            End If

            '
            'dstevents = ReturnDataset(eventssql)

            stragesql += eventssql
            dststorage = ReturnDataset(stragesql)

            ' If dststorage.Tables(0).Rows.Count > 0 Then
            Me.DataGridViewstoragedetail.DataSource = dststorage.Tables(0)
            'End If
            'If dststorage.Tables(0).Rows.Count > 0 Then
            Me.DGVevent.DataSource = dststorage.Tables(1)
            ' End If

        Catch ex As Exception
            MessageBox.Show(Err.Description + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Frm.Dispose()
        End Try

    End Sub

    Private Sub Btnunaddnew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnunaddnew.Click
        Try
            If Me.Txtcurrentperiod.Text.Length = 0 Then
                MessageBox.Show("請核對當前期別", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            Dim Fperiod As String = Trim(Me.Txtcurrentperiod.Text)
            Dim Strstorage As String = ""
            Dim Cnnstoragecheck As SqlClient.SqlConnection = New SqlClient.SqlConnection
            Dim Cmdstoragecheck As SqlClient.SqlCommand = New SqlClient.SqlCommand


            Cnnstoragecheck = GetConn()

            If Cnnstoragecheck.State = ConnectionState.Closed Then
                Cnnstoragecheck.Open()
            End If

            Dim Transstoragecheck As SqlClient.SqlTransaction = Cnnstoragecheck.BeginTransaction
            Try
                Strstorage = "update stor_storagehistory  set inqty= 0,inprice=0 , inamount=0,outqty=0,outprice=0,outamount=0,endqty=0,endprice=0,endamount=0 where storehouse='" & PubCompanyCode & "' and period='" & Fperiod & "'" & vbCrLf
                Strstorage += "update bsc_systemprofile  set  fvalue='1' where Fcategory='store' and Fkey= 'period_' + '" & PubCompanyCode & "'+'_status' " & vbCrLf
                Strstorage += "update BSC_StoreHouse set  fstatus='0' where fcode='" & PubCompanyCode & "'" & vbCrLf
                Strstorage += "insert into dbo.Stor_StorageOperationevents(period,storehouse,management,operator,operatetime,computername)values('" & Fperiod & "','" & PubCompanyCode & "','Undo','" & PubUserName & "',convert(varchar(19),getdate(),21),'" & My.Computer.Name & "')"

                With Cmdstoragecheck
                    .CommandText = Strstorage
                    .Connection = Cnnstoragecheck
                    .Transaction = Transstoragecheck
                    .ExecuteNonQuery()
                End With
                Transstoragecheck.Commit()

                MessageBox.Show("反関賬成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.Btnunaddnew.Enabled = False
                Me.Btnpass.Enabled = False
                Me.btnaddnew.Enabled = True
            Catch ex As Exception
                Transstoragecheck.Rollback()
                MessageBox.Show(Err.Description + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try

        Catch ex As Exception
            MessageBox.Show(Err.Description + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub Btnpass_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnpass.Click
        Me.Cursor = Cursors.WaitCursor
        Try


            If MessageBox.Show("您確定要過帳嗎？　過賬以後期別將改為下一期別，本期庫存不能再修改", Msg.CompanyName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) = DialogResult.Yes Then

                '         If Me.Txtcurrentperiod.Text.Length = 0 Then



                Dim Fperiod As String = Trim(Me.Txtcurrentperiod.Text)
                Dim storagehistorycnn As New SqlClient.SqlConnection
                Dim ds As New SqlClient.SqlCommand

                '判斷是否已經盤點
                Dim Isexitsql As String
                Dim Isexitrst As New DataSet
                Isexitsql = "select * from  Store_CheckMaster where period='" & Fperiod & "' and storehouse='" & PubCompanyCode & "' and isnull(status,0)=1 "
                Isexitrst = ReturnDataset(Isexitsql)
                If Isexitrst.Tables(0).Rows.Count < 1 Then
                    MessageBox.Show("您還沒有盤點，不可以過帳！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If
                storagehistorycnn = GetConn()
                If storagehistorycnn.State = ConnectionState.Closed Then
                    storagehistorycnn.Open()
                End If

                Dim strsql As String = ""
                strsql = "exec storagecopy '" & PubCompanyCode & "','" & Fperiod & "','" & PubCompanyCode & "','" & My.Computer.Name & "'"
                'strsql = "exec storagecopy '" & PubCompanyCode & "','" & Fperiod & "'" & vbCrLf
                With ds
                    .CommandText = strsql
                    .Connection = storagehistorycnn
                    .ExecuteNonQuery()
                End With
                Me.Btnpass.Enabled = False
                Me.btnaddnew.Enabled = True
                Me.Btnunaddnew.Enabled = False
                'Me.Txtcurrentperiod.Text = DateAdd(DateInterval.Month, 1, CType(Fperiod + "01", Date)).ToString.Substring(1, 6)
                Dim NewPeriod As String = Fperiod.Trim & "01"
                If NewPeriod.Length = 8 Then
                    Me.Txtcurrentperiod.Text = Format(DateAdd(DateInterval.Month, 1, CType(Convert.ToInt32(NewPeriod).ToString("####-##-##"), Date)), "yyyyMM")
                End If
                MessageBox.Show("過帳成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                'End If
            End If
        Catch ex As Exception
            MessageBox.Show(Err.Description + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub
End Class
